<template>
  <div class="min-h-screen py-8 px-4 sm:px-6 lg:px-8">
    <div class="max-w-7xl mx-auto">
      <!-- 页面标题 -->
      <div class="text-center mb-12">
        <h1 class="text-4xl font-bold mb-4 tech-text">IndexedDB API</h1>
        <p class="text-gray-300 text-lg">
          浏览器端的强大 NoSQL 数据库，支持大量结构化数据的存储和查询
        </p>
      </div>

      <!-- 浏览器支持提示 -->
      <div v-if="!isSupported" class="tech-card mb-8 border-yellow-600">
        <div class="flex items-center mb-4">
          <i class="i-carbon-warning text-yellow-500 text-xl mr-3"></i>
          <h3 class="text-xl font-semibold text-yellow-500">浏览器支持提示</h3>
        </div>
        <p class="text-gray-300">
          您的浏览器不支持 IndexedDB API。此功能需要现代浏览器支持。
        </p>
      </div>

      <!-- 数据库状态 -->
      <div class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">数据库状态</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="bg-gray-800 rounded-lg p-6">
            <div class="flex items-center mb-3">
              <i class="i-carbon-database text-3xl text-tech-accent mr-3"></i>
              <div>
                <div class="text-gray-400 text-sm">数据库状态</div>
                <div class="text-white text-xl font-semibold">
                  {{ db ? '已连接' : '未连接' }}
                </div>
              </div>
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div class="flex items-center mb-3">
              <i class="i-carbon-document text-3xl text-green-400 mr-3"></i>
              <div>
                <div class="text-gray-400 text-sm">记录总数</div>
                <div class="text-white text-xl font-semibold">
                  {{ records.length }}
                </div>
              </div>
            </div>
          </div>

          <div class="bg-gray-800 rounded-lg p-6">
            <div class="flex items-center mb-3">
              <i class="i-carbon-data-base text-3xl text-blue-400 mr-3"></i>
              <div>
                <div class="text-gray-400 text-sm">数据库版本</div>
                <div class="text-white text-xl font-semibold">
                  {{ db?.version || '-' }}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div class="mt-6 flex gap-3">
          <button
            v-if="!db"
            @click="initDB"
            class="tech-button"
          >
            <i class="i-carbon-connect mr-2"></i>
            初始化数据库
          </button>
          <button
            v-else
            @click="closeDB"
            class="bg-yellow-600 hover:bg-yellow-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-close mr-2"></i>
            关闭连接
          </button>
          <button
            @click="deleteDatabase"
            class="bg-red-600 hover:bg-red-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-trash-can mr-2"></i>
            删除数据库
          </button>
        </div>
      </div>

      <!-- 添加记录 -->
      <div v-if="db" class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">添加记录</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
          <div class="space-y-4">
            <div>
              <label class="text-white font-medium mb-2 block">姓名</label>
              <input
                v-model="newRecord.name"
                type="text"
                placeholder="输入姓名"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">邮箱</label>
              <input
                v-model="newRecord.email"
                type="email"
                placeholder="输入邮箱"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">年龄</label>
              <input
                v-model.number="newRecord.age"
                type="number"
                placeholder="输入年龄"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>
          </div>

          <div class="space-y-4">
            <div>
              <label class="text-white font-medium mb-2 block">职业</label>
              <input
                v-model="newRecord.occupation"
                type="text"
                placeholder="输入职业"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">城市</label>
              <input
                v-model="newRecord.city"
                type="text"
                placeholder="输入城市"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">备注</label>
              <textarea
                v-model="newRecord.notes"
                placeholder="输入备注信息"
                rows="3"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none resize-none"
              ></textarea>
            </div>
          </div>
        </div>

        <div class="mt-6 flex gap-3">
          <button
            @click="addRecord"
            class="tech-button"
          >
            <i class="i-carbon-add mr-2"></i>
            添加记录
          </button>
          <button
            @click="addBatchRecords"
            class="bg-green-600 hover:bg-green-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-data-set mr-2"></i>
            添加示例数据
          </button>
          <button
            @click="clearForm"
            class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-3 rounded-lg transition-colors"
          >
            <i class="i-carbon-clean mr-2"></i>
            清空表单
          </button>
        </div>
      </div>

      <!-- 搜索和筛选 -->
      <div v-if="db && records.length > 0" class="tech-card mb-8">
        <h2 class="text-2xl font-semibold mb-6 text-white">搜索和筛选</h2>
        
        <div class="grid grid-cols-1 md:grid-cols-3 gap-4">
          <div>
            <label class="text-white font-medium mb-2 block">搜索关键词</label>
            <input
              v-model="searchQuery"
              type="text"
              placeholder="搜索姓名、邮箱或职业"
              class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
            >
          </div>

          <div>
            <label class="text-white font-medium mb-2 block">城市筛选</label>
            <select
              v-model="filterCity"
              class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
            >
              <option value="">所有城市</option>
              <option v-for="city in uniqueCities" :key="city" :value="city">
                {{ city }}
              </option>
            </select>
          </div>

          <div>
            <label class="text-white font-medium mb-2 block">年龄范围</label>
            <select
              v-model="filterAge"
              class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
            >
              <option value="">所有年龄</option>
              <option value="0-25">0-25岁</option>
              <option value="26-35">26-35岁</option>
              <option value="36-50">36-50岁</option>
              <option value="51-100">51岁以上</option>
            </select>
          </div>
        </div>

        <div class="mt-4 flex items-center justify-between">
          <div class="text-gray-300">
            找到 <span class="text-tech-accent font-semibold">{{ filteredRecords.length }}</span> 条记录
          </div>
          <button
            @click="clearFilters"
            class="text-tech-accent hover:text-tech-accent/80 transition-colors"
          >
            <i class="i-carbon-filter-remove mr-1"></i>
            清除筛选
          </button>
        </div>
      </div>

      <!-- 记录列表 -->
      <div v-if="db && records.length > 0" class="tech-card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-semibold text-white">记录列表</h2>
          <button
            @click="clearAllRecords"
            class="bg-red-600 hover:bg-red-700 text-white px-4 py-2 rounded-lg transition-colors text-sm"
          >
            <i class="i-carbon-trash-can mr-1"></i>
            清空所有记录
          </button>
        </div>

        <div class="overflow-x-auto">
          <table class="w-full">
            <thead>
              <tr class="border-b border-gray-700">
                <th class="text-left py-3 px-4 text-gray-400 font-medium">ID</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">姓名</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">邮箱</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">年龄</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">职业</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">城市</th>
                <th class="text-left py-3 px-4 text-gray-400 font-medium">创建时间</th>
                <th class="text-right py-3 px-4 text-gray-400 font-medium">操作</th>
              </tr>
            </thead>
            <tbody>
              <tr
                v-for="record in filteredRecords"
                :key="record.id"
                class="border-b border-gray-800 hover:bg-gray-800/50 transition-colors"
              >
                <td class="py-3 px-4 text-white">{{ record.id }}</td>
                <td class="py-3 px-4 text-white">{{ record.name }}</td>
                <td class="py-3 px-4 text-gray-300">{{ record.email }}</td>
                <td class="py-3 px-4 text-gray-300">{{ record.age }}</td>
                <td class="py-3 px-4 text-gray-300">{{ record.occupation }}</td>
                <td class="py-3 px-4 text-gray-300">{{ record.city }}</td>
                <td class="py-3 px-4 text-gray-400 text-sm">
                  {{ formatDate(record.createdAt) }}
                </td>
                <td class="py-3 px-4 text-right">
                  <button
                    @click="editRecord(record)"
                    class="text-blue-400 hover:text-blue-300 mr-3"
                    title="编辑"
                  >
                    <i class="i-carbon-edit text-lg"></i>
                  </button>
                  <button
                    @click="deleteRecord(record.id!)"
                    class="text-red-400 hover:text-red-300"
                    title="删除"
                  >
                    <i class="i-carbon-trash-can text-lg"></i>
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>

      <!-- 空状态 -->
      <div v-if="db && records.length === 0" class="tech-card mb-8">
        <div class="text-center py-12 text-gray-400">
          <i class="i-carbon-data-base text-6xl mb-4 block mx-auto opacity-50"></i>
          <p class="text-lg mb-2">暂无数据</p>
          <p class="text-sm">点击上方"添加记录"或"添加示例数据"按钮开始</p>
        </div>
      </div>

      <!-- 编辑模态框 -->
      <div
        v-if="editingRecord"
        class="fixed inset-0 bg-black bg-opacity-75 z-50 flex items-center justify-center p-4"
        @click.self="cancelEdit"
      >
        <div class="bg-gray-900 rounded-lg max-w-2xl w-full p-6">
          <div class="flex justify-between items-center mb-6">
            <h3 class="text-2xl font-semibold text-white">编辑记录</h3>
            <button
              @click="cancelEdit"
              class="text-gray-400 hover:text-white"
            >
              <i class="i-carbon-close text-2xl"></i>
            </button>
          </div>

          <div class="grid grid-cols-1 md:grid-cols-2 gap-4 mb-6">
            <div>
              <label class="text-white font-medium mb-2 block">姓名</label>
              <input
                v-model="editingRecord.name"
                type="text"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">邮箱</label>
              <input
                v-model="editingRecord.email"
                type="email"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">年龄</label>
              <input
                v-model.number="editingRecord.age"
                type="number"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">职业</label>
              <input
                v-model="editingRecord.occupation"
                type="text"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div>
              <label class="text-white font-medium mb-2 block">城市</label>
              <input
                v-model="editingRecord.city"
                type="text"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none"
              >
            </div>

            <div class="md:col-span-2">
              <label class="text-white font-medium mb-2 block">备注</label>
              <textarea
                v-model="editingRecord.notes"
                rows="3"
                class="w-full bg-gray-800 text-white px-4 py-3 rounded-lg border border-gray-700 focus:border-tech-accent outline-none resize-none"
              ></textarea>
            </div>
          </div>

          <div class="flex gap-3">
            <button
              @click="saveEdit"
              class="tech-button flex-1"
            >
              <i class="i-carbon-checkmark mr-2"></i>
              保存修改
            </button>
            <button
              @click="cancelEdit"
              class="bg-gray-600 hover:bg-gray-700 text-white px-6 py-3 rounded-lg transition-colors flex-1"
            >
              <i class="i-carbon-close mr-2"></i>
              取消
            </button>
          </div>
        </div>
      </div>

      <!-- 操作日志 -->
      <div v-if="logs.length > 0" class="tech-card mb-8">
        <div class="flex justify-between items-center mb-6">
          <h2 class="text-2xl font-semibold text-white">操作日志</h2>
          <button
            @click="clearLogs"
            class="text-red-400 hover:text-red-300 text-sm"
          >
            <i class="i-carbon-clean mr-1"></i>
            清空日志
          </button>
        </div>

        <div class="space-y-2 max-h-64 overflow-y-auto">
          <div
            v-for="(log, index) in logs.slice().reverse()"
            :key="index"
            class="bg-gray-800 rounded-lg p-3 flex items-start"
          >
            <i
              :class="getLogIcon(log.type)"
              class="text-xl mr-3 mt-1"
            ></i>
            <div class="flex-1">
              <div class="text-white font-medium">{{ log.message }}</div>
              <div class="text-gray-400 text-sm mt-1">{{ log.timestamp }}</div>
            </div>
          </div>
        </div>
      </div>

      <!-- API 信息 -->
      <div class="tech-card">
        <h3 class="text-xl font-semibold mb-4 text-white">API 信息</h3>
        <div class="space-y-4 text-gray-300">
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">浏览器支持</h4>
            <p>所有现代浏览器都支持 IndexedDB API</p>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">主要特性</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>存储大量结构化数据（包括文件/blob）</li>
              <li>使用索引实现高性能搜索</li>
              <li>支持事务处理，保证数据完整性</li>
              <li>异步 API，不会阻塞主线程</li>
              <li>支持版本管理和数据库升级</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">核心概念</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">Database</code> - 数据库实例</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">Object Store</code> - 对象存储空间（类似表）</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">Index</code> - 索引，用于快速查询</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">Transaction</code> - 事务，确保操作原子性</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">Cursor</code> - 游标，用于遍历数据</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">常用操作</h4>
            <ul class="list-disc list-inside space-y-1">
              <li><code class="bg-gray-800 px-2 py-1 rounded">add()</code> - 添加数据</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">put()</code> - 更新或添加数据</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">get()</code> - 获取数据</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">delete()</code> - 删除数据</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">clear()</code> - 清空对象存储</li>
              <li><code class="bg-gray-800 px-2 py-1 rounded">getAll()</code> - 获取所有数据</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">使用场景</h4>
            <ul class="list-disc list-inside space-y-1">
              <li>离线应用数据存储</li>
              <li>PWA 应用数据缓存</li>
              <li>大文件和媒体资源存储</li>
              <li>用户偏好设置保存</li>
              <li>复杂数据结构的本地存储</li>
              <li>离线优先的应用架构</li>
            </ul>
          </div>
          <div>
            <h4 class="font-semibold text-tech-accent mb-2">存储限制</h4>
            <p class="text-sm">
              IndexedDB 的存储空间取决于浏览器和设备的可用空间。
              Chrome 允许使用磁盘可用空间的 60%（最多 20GB），
              Firefox 允许使用 50%（最多 10GB）。
              达到限制后，浏览器会请求用户授权。
            </p>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'

// 类型定义
interface Record {
  id?: number
  name: string
  email: string
  age: number
  occupation: string
  city: string
  notes: string
  createdAt: number
}

interface Log {
  type: 'success' | 'error' | 'info'
  message: string
  timestamp: string
}

// 常量
const DB_NAME = 'MDN_Demo_DB'
const DB_VERSION = 1
const STORE_NAME = 'users'

// 响应式状态
const isSupported = ref('indexedDB' in window)
const db = ref<IDBDatabase | null>(null)
const records = ref<Record[]>([])
const logs = ref<Log[]>([])

// 表单
const newRecord = ref<Record>({
  name: '',
  email: '',
  age: 0,
  occupation: '',
  city: '',
  notes: '',
  createdAt: Date.now()
})

// 编辑
const editingRecord = ref<Record | null>(null)

// 搜索和筛选
const searchQuery = ref('')
const filterCity = ref('')
const filterAge = ref('')

// 初始化
onMounted(() => {
  if (isSupported.value) {
    initDB()
  }
})

// 初始化数据库
const initDB = () => {
  const request = indexedDB.open(DB_NAME, DB_VERSION)

  request.onerror = () => {
    addLog('error', '数据库打开失败')
  }

  request.onsuccess = (event) => {
    db.value = (event.target as IDBOpenDBRequest).result
    addLog('success', '数据库连接成功')
    loadRecords()
  }

  request.onupgradeneeded = (event) => {
    const database = (event.target as IDBOpenDBRequest).result

    // 创建对象存储
    if (!database.objectStoreNames.contains(STORE_NAME)) {
      const objectStore = database.createObjectStore(STORE_NAME, {
        keyPath: 'id',
        autoIncrement: true
      })

      // 创建索引
      objectStore.createIndex('name', 'name', { unique: false })
      objectStore.createIndex('email', 'email', { unique: true })
      objectStore.createIndex('city', 'city', { unique: false })
      objectStore.createIndex('age', 'age', { unique: false })

      addLog('info', '数据库结构创建成功')
    }
  }
}

// 关闭数据库
const closeDB = () => {
  if (db.value) {
    db.value.close()
    db.value = null
    records.value = []
    addLog('info', '数据库连接已关闭')
  }
}

// 删除数据库
const deleteDatabase = () => {
  if (confirm('确定要删除整个数据库吗？此操作不可恢复！')) {
    closeDB()
    
    const request = indexedDB.deleteDatabase(DB_NAME)
    
    request.onsuccess = () => {
      addLog('success', '数据库已删除')
      records.value = []
    }
    
    request.onerror = () => {
      addLog('error', '数据库删除失败')
    }
  }
}

// 加载所有记录
const loadRecords = () => {
  if (!db.value) return

  const transaction = db.value.transaction([STORE_NAME], 'readonly')
  const objectStore = transaction.objectStore(STORE_NAME)
  const request = objectStore.getAll()

  request.onsuccess = () => {
    records.value = request.result
  }

  request.onerror = () => {
    addLog('error', '加载记录失败')
  }
}

// 添加记录
const addRecord = () => {
  if (!db.value) return

  if (!newRecord.value.name || !newRecord.value.email) {
    alert('请填写姓名和邮箱')
    return
  }

  const transaction = db.value.transaction([STORE_NAME], 'readwrite')
  const objectStore = transaction.objectStore(STORE_NAME)
  
  const recordToAdd = {
    ...newRecord.value,
    createdAt: Date.now()
  }
  
  const request = objectStore.add(recordToAdd)

  request.onsuccess = () => {
    addLog('success', `添加记录成功: ${newRecord.value.name}`)
    loadRecords()
    clearForm()
  }

  request.onerror = () => {
    addLog('error', '添加记录失败（可能邮箱重复）')
  }
}

// 批量添加示例数据
const addBatchRecords = () => {
  if (!db.value) return

  const sampleData: Omit<Record, 'id'>[] = [
    {
      name: '张三',
      email: 'zhangsan@example.com',
      age: 28,
      occupation: '软件工程师',
      city: '北京',
      notes: '前端开发专家',
      createdAt: Date.now()
    },
    {
      name: '李四',
      email: 'lisi@example.com',
      age: 32,
      occupation: '产品经理',
      city: '上海',
      notes: '擅长用户体验设计',
      createdAt: Date.now()
    },
    {
      name: '王五',
      email: 'wangwu@example.com',
      age: 25,
      occupation: 'UI设计师',
      city: '深圳',
      notes: '精通视觉设计',
      createdAt: Date.now()
    },
    {
      name: '赵六',
      email: 'zhaoliu@example.com',
      age: 35,
      occupation: '项目经理',
      city: '杭州',
      notes: 'PMP认证',
      createdAt: Date.now()
    },
    {
      name: '钱七',
      email: 'qianqi@example.com',
      age: 29,
      occupation: '后端工程师',
      city: '成都',
      notes: 'Java专家',
      createdAt: Date.now()
    }
  ]

  const transaction = db.value.transaction([STORE_NAME], 'readwrite')
  const objectStore = transaction.objectStore(STORE_NAME)

  sampleData.forEach(data => {
    objectStore.add(data)
  })

  transaction.oncomplete = () => {
    addLog('success', `批量添加 ${sampleData.length} 条记录成功`)
    loadRecords()
  }

  transaction.onerror = () => {
    addLog('error', '批量添加记录失败')
  }
}

// 编辑记录
const editRecord = (record: Record) => {
  editingRecord.value = { ...record }
}

// 保存编辑
const saveEdit = () => {
  if (!db.value || !editingRecord.value) return

  const transaction = db.value.transaction([STORE_NAME], 'readwrite')
  const objectStore = transaction.objectStore(STORE_NAME)
  const request = objectStore.put(editingRecord.value)

  request.onsuccess = () => {
    addLog('success', `更新记录成功: ${editingRecord.value!.name}`)
    loadRecords()
    cancelEdit()
  }

  request.onerror = () => {
    addLog('error', '更新记录失败')
  }
}

// 取消编辑
const cancelEdit = () => {
  editingRecord.value = null
}

// 删除记录
const deleteRecord = (id: number) => {
  if (!db.value) return

  if (!confirm('确定要删除这条记录吗？')) return

  const transaction = db.value.transaction([STORE_NAME], 'readwrite')
  const objectStore = transaction.objectStore(STORE_NAME)
  const request = objectStore.delete(id)

  request.onsuccess = () => {
    addLog('success', '删除记录成功')
    loadRecords()
  }

  request.onerror = () => {
    addLog('error', '删除记录失败')
  }
}

// 清空所有记录
const clearAllRecords = () => {
  if (!db.value) return

  if (!confirm('确定要清空所有记录吗？')) return

  const transaction = db.value.transaction([STORE_NAME], 'readwrite')
  const objectStore = transaction.objectStore(STORE_NAME)
  const request = objectStore.clear()

  request.onsuccess = () => {
    addLog('success', '清空所有记录成功')
    loadRecords()
  }

  request.onerror = () => {
    addLog('error', '清空记录失败')
  }
}

// 清空表单
const clearForm = () => {
  newRecord.value = {
    name: '',
    email: '',
    age: 0,
    occupation: '',
    city: '',
    notes: '',
    createdAt: Date.now()
  }
}

// 筛选记录
const filteredRecords = computed(() => {
  let result = records.value

  // 关键词搜索
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(record =>
      record.name.toLowerCase().includes(query) ||
      record.email.toLowerCase().includes(query) ||
      record.occupation.toLowerCase().includes(query)
    )
  }

  // 城市筛选
  if (filterCity.value) {
    result = result.filter(record => record.city === filterCity.value)
  }

  // 年龄筛选
  if (filterAge.value) {
    const [min, max] = filterAge.value.split('-').map(Number)
    result = result.filter(record => record.age >= min && record.age <= max)
  }

  return result
})

// 获取所有城市
const uniqueCities = computed(() => {
  return [...new Set(records.value.map(r => r.city))].filter(Boolean).sort()
})

// 清除筛选
const clearFilters = () => {
  searchQuery.value = ''
  filterCity.value = ''
  filterAge.value = ''
}

// 添加日志
const addLog = (type: 'success' | 'error' | 'info', message: string) => {
  logs.value.push({
    type,
    message,
    timestamp: new Date().toLocaleString('zh-CN')
  })

  // 只保留最近50条
  if (logs.value.length > 50) {
    logs.value.shift()
  }
}

// 清空日志
const clearLogs = () => {
  logs.value = []
}

// 获取日志图标
const getLogIcon = (type: string) => {
  const icons = {
    success: 'i-carbon-checkmark-filled text-green-400',
    error: 'i-carbon-error-filled text-red-400',
    info: 'i-carbon-information-filled text-blue-400'
  }
  return icons[type as keyof typeof icons]
}

// 格式化日期
const formatDate = (timestamp: number): string => {
  return new Date(timestamp).toLocaleString('zh-CN')
}
</script>

